package com.tmc.service.intcar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.intcar.EthDriver;
import com.tmc.bean.intcar.EthQueryDriverReq;
import com.tmc.bean.intcar.EthQueryDriverResp;
import com.tmc.entity.intcar.IntcarDriver;
import com.tmc.entity.intcar.IntcarOrder;
import com.tmc.util.ObjectUtil;
import com.tmc.vendor.intcar.common.ServiceCenter;
import com.tmc.vendor.intcar.common.VendorService;

/**
 * @author zhang
 * @date 2017年12月26日 下午6:42:04 
 */
@Service
public class IntcarQueryDriverServiceImpl {
	
	private Log log = LogFactory.getLog(IntcarQueryDriverServiceImpl.class);
	
	@Autowired
	private IntcarOrderServiceImpl orderService;
	
	public CommonResult queryDriver(ContextInfo context, EthQueryDriverReq req){
		IntcarOrder dbOrder = orderService.getById(context, req.getOrderID());
		if(dbOrder == null){
			return CommonResult.makeFail("ID为"+req.getOrderID()+"的订单不存在！");
		}
		VendorService service = ServiceCenter.getService(dbOrder.getVendor());
		EthQueryDriverResp resp = null;
		try {
			//TODO  此处逻辑需设置定时器，定时查询是否委派司导！
			resp = service.queryDriver(context, req);
			if(resp.isSuccess()){
				IntcarDriver driver = buildDriver(dbOrder, resp.getDriver());
				dbOrder.setDriver(driver);
				// TODO 更新订单状态！
				CommonResult result = orderService.pushDriver(context, dbOrder);
				return result;
			}
			return CommonResult.makeFail(resp.getMessage());
		} catch (Exception e) {
			log.error("查询司导出错！", e);
		}
		return CommonResult.makeFail("查询司导出错！");
	}
	
	private IntcarDriver buildDriver(IntcarOrder order, EthDriver driver) {
		IntcarDriver bean = ObjectUtil.makeTargetBean(driver, IntcarDriver.class);
		bean.setOrderID(order.getOrderID());
		return bean;
	}
	
}
